/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  BaseCommand,
  cadAppLog,
  CENTEREVENTS,
  CommandDialog,
  EventsRes,
  KEYBOARD_KEY,
  pickedFaceData,
  Types,
} from '@amcax/base';
import {
  MultiPickInput,
  PickInputValueType,
} from '@app-cad/common/components/pick-input/3d';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { docMgr, userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { Button } from 'antd';
import i18n from 'i18next';
import { useEffect, useRef } from 'react';

import { eventCenterManager } from '@app-base/common/events/EventCenterManager';
import { SKETCH_EVENT } from '@app-cad/common/Constants';
import { getIdOfPickedObj } from '@app-base/common/utils/render';
import { enterSketch } from '@app-base/common/utils';

function SketchDialog({
  title,
  onClose,
  skipCameraChange = false,
}: {
  title: string;
  // 当进入checker时，result为true表示继续，false表示退出
  // src\pages\pre-checker\sketch-pre-checker.ts
  onClose: (result: boolean) => void;
  skipCameraChange?: boolean;
}) {
  useCommand('sketch-dialog', {
    onClose: () => {},
  });

  const enteringSketchRef = useRef(false);
  useEffect(() => {
    eventCenterManager.activeEventCenter.on(CENTEREVENTS.KEYUP, onKeyUp);
    return () => {
      eventCenterManager.activeEventCenter.off(CENTEREVENTS.KEYUP, onKeyUp);
    };
  }, []);
  const onKeyUp = async (e: EventsRes<KeyboardEvent>) => {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose(false);
    }
  };
  useEffect(() => {
    userEvents.on(SKETCH_EVENT.SKETCH_ENTER_EDIT, (isClick: boolean) => {
      if (isClick) {
        onClose(true);
      }
    });

    return () => {
      userEvents.off(SKETCH_EVENT.SKETCH_ENTER_EDIT);
    };
  }, []);
  const createSketchAndSwitchEnvironment = async (
    pickedObject: pickedFaceData,
  ) => {
    if (enteringSketchRef.current) {
      return;
    }

    const documentObject = docMgr.getDocumentObjectById(
      pickedObject?.idInfo?.o,
    );

    if (documentObject.type === Types.Sketcher) {
      return;
    }

    enteringSketchRef.current = true;

    try {
      // 选中某个面后，进入草图
      cadAppLog('Picked Face:', pickedObject);
      const result = await wsApi.createSketcher(getIdOfPickedObj(pickedObject));

      cadAppLog('Sketch Create Result:', result);
      await docMgr.updateDocumentObjects();
      const sketch = docMgr.getDocumentObjectById(result.id);
      enterSketch({
        frame: sketch.frame,
        sketchId: result.id,
        skipCameraChange,
      });
      docMgr.setLocalReferenceVisibility('ORIGIN', false);
      onClose(true);
    } catch (error) {
      console.error(error);
    } finally {
      enteringSketchRef.current = false;
    }
  };
  return (
    <CommandDialog
      title={title}
      onClose={() => onClose(false)}
      placement='topLeft'
      actions={[
        <Button
          key={0}
          onClick={() => onClose(false)}
        >
          关闭
        </Button>,
      ]}
    >
      <MultiPickInput
        placeholder='选择一个基准面、平面用于绘制草图。'
        value={[]}
        autoFocus
        className='w-[280px]'
        onPick={(v) => createSketchAndSwitchEnvironment(v[0] as pickedFaceData)}
        allowPickType={[PickInputValueType.Plane]}
      />
    </CommandDialog>
  );
}

export const cmdSketchIn: BaseCommand = {
  id: 'CmdSketchIn',
  label: 'command.sketchIn',
  icon: 'commands/feature/sketch-in',
  help: {
    remark: 'tips.redo',
    // preview: '/help/Redo.gif'
  },
  create: (label, onClose, _, customParam) => (
    <SketchDialog
      title={i18n.t(label)}
      onClose={onClose}
      skipCameraChange={customParam?.skipCameraChange ?? false}
    />
  ),
};
